<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
      <el-form-item label="模具" prop="accountId">
        <el-select v-model="formData.accountId" filterable clearable placeholder="请选择模具" style="width: 100%;"
          @change="handleAccountChange">
          <el-option v-for="account in accountList" :key="account.id" :label="account.code + '(' + account.name + ')'"
            :value="account.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="复检类型" prop="recheckId" required>
        <el-select v-model="formData.recheckId" placeholder="请选择复检类型" class="!w-240px" filterable clearable
          :disabled="isRecheckTypeDisabled">
          <el-option v-for="item in recheckCategoryOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="是否临时复检" prop="ifTmp">
        <el-radio-group v-model="formData.ifTmp" class="ml-4">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="0">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { RecheckTobeApi, RecheckTobe } from '@/api/mold/rechecktobe'
import { AccountApi, Account } from '@/api/mold/account'
import { RecheckCategoryApi } from '@/api/mold/recheckcategory'

/** 待复检 表单 */
defineOptions({ name: 'RecheckTobeForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  accountId: undefined,
  drawingNoId: undefined,
  recheckId: undefined,
  lastRecheckTime: undefined,
  ifTmp: 1,
  status: undefined,
  taskId: undefined,
  itemId: undefined,
  remindF: undefined,
})
const formRules = reactive({
  accountId: [{ required: true, message: '模具不能为空', trigger: 'blur' }],
  recheckId: [{ required: true, message: '复检类型不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

const accountList = ref()
const recheckCategoryOptions = ref([])

// 控制复检类型是否禁用
const isRecheckTypeDisabled = computed(() => {
  if (!formData.value.accountId) return false

  const selectedAccount = accountList.value?.find(
    (account: any) => account.id === formData.value.accountId
  )

  return selectedAccount?.recheckId !== null && selectedAccount?.recheckId !== undefined
})

/** 加载复检类型选项 */
const loadRecheckCategories = async () => {
  try {
    const data = await RecheckCategoryApi.getRecheckCategoryAll()

    if (data && Array.isArray(data)) {
      recheckCategoryOptions.value = data.map(item => ({
        value: item.id,
        label: `${item.name} (${item.code})`
      }))
    } else {
      console.error('复检类型数据格式不正确:', data)
      ElMessage.error('加载复检类型失败: 数据格式不正确')
    }
  } catch (error) {
    console.error('加载复检类型失败:', error)
    ElMessage.error('加载复检类型失败')
  }
}

/** 处理模具选择变化 */
const handleAccountChange = (accountId: number) => {
  if (!accountId) {
    formData.value.recheckId = undefined
    return
  }

  const selectedAccount = accountList.value?.find(
    (account: any) => account.id === accountId
  )

  // 如果选择的模具有 recheckId，则自动设置复检类型并锁定选择
  if (selectedAccount?.recheckId !== null && selectedAccount?.recheckId !== undefined) {
    formData.value.recheckId = selectedAccount.recheckId
  } else {
    // 如果模具没有预设 recheckId，则保持当前选择或清空
  }
}

/** 获得模具列表 */
const getAccountList = async () => {
  accountList.value = []
  const data = await AccountApi.getAccountAll()
  accountList.value = data
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  await getAccountList()
  await loadRecheckCategories()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await RecheckTobeApi.getRecheckTobe(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RecheckTobe
    if (formType.value === 'create') {
      await RecheckTobeApi.createRecheckTobe(data)
      message.success(t('common.createSuccess'))
    } else {
      await RecheckTobeApi.updateRecheckTobe(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    accountId: undefined,
    drawingNoId: undefined,
    recheckId: undefined,
    lastRecheckTime: undefined,
    ifTmp: 1,
    status: undefined,
    taskId: undefined,
    itemId: undefined,
    remindF: undefined,
  }
  formRef.value?.resetFields()
}
</script>